<template>
    <el-dialog v-model="quotation" title="Add to Quotation" width="79%"
        style="position: absolute;top:-80px;left:0;right:0; height:85vh">
        <div class="flex addQuotation">
            <div class="flex fdc addLeft">
                <div class="brs bs pt-10  pl-10 pr-10 ">
                    <el-select v-model="PI_name" filterable :remote-method="OrderCapture" remote @visible-change="visible"
                        @change="orderChange" style="width: 25%;" placeholder="Please select the order">
                        <el-option v-for="item in orderList" :key="item.PI_name" :label="item.PI_name"
                            :value="item.order_id" />
                    </el-select>
                    <div class="flex jc-sb mt-10">
                        <p class="mt-10 f16 fa5">Add items to order</p>
                        <el-button type="primary" plain class="add" @click="add">Add</el-button>
                    </div>
                    <el-table ref="multipleTableRef" :data="quotationTable" v-loading="loading" @row-click="graph"
                        height="36vh" style="width: 100%;" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="30" />
                        <el-table-column property="product_name_pi" align="center" label="MODEL" min-width="140" />
                        <el-table-column property="Brand_name" align="center" label="BRAND" />
                        <el-table-column property="quantity" align="center" label="Qty" />
                        <el-table-column prop="price" align="center" label="PRICE" />
                        <el-table-column property="leadingtime" align="center" label="LEADING" />
                        <el-table-column property="product_condition" align="center" label="CONDITION" min-width="120" />
                    </el-table>
                </div>
                <div ref="price" v-loading="historyQuotation" class="w100p mt-10 brs bs pt-10 pb-10 pl-10 pr-10"
                    style="height: 29vh;"></div>
            </div>

            <!-- 右边 -->
            <div class="rightPrice">
                <div class="bs brs pt-10 pl-10 pr-10">
                    <div class="flex jc-sb ">
                        <div>
                            <el-select v-show="store.type == 2" v-model="profit" @change="unifiedProfit" class="ml-10 w60p"
                                placeholder="Profit">
                                <el-option v-for="item in profitArr" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                            <el-select v-show="store.type == 3" v-model="leading" @change="unifiedLeading"
                                class="ml-10 w60p" placeholder="Bulk selection pointer">
                                <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                    :value="item.label" />
                            </el-select>
                        </div>
                        <div>
                            <el-button plain @click="Added">New</el-button>
                            <el-button type="primary" plain @click="save">Save</el-button>
                            <el-popconfirm title="Sure to delete?" @confirm="delGoods">
                                <template #reference>
                                    <el-button type="primary" class="del" plain>Delete</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </div>

                    <!--表格 -->
                    <div class="boxTable w100p mt-10">
                        <div v-loading="loading" class="table">
                            <p class="tabTitle flex aic ml-10 pt-5 pb-5"
                                style="border-bottom: 1px solid #EBEEF5; color:#909399">
                                <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
                                    @change="handleCheckAllChange"><br></el-checkbox>
                                <span class="ml-5" style="width: 13%;">MODEL</span>
                                <span style="width: 12.8%;">BRAND</span>
                                <span style="width: 5%;">QTY</span>
                                <!-- <span :class="{ 'w12p': store.type != 3, 'w12p': store.type == 3 }">MultipleBuyer</span> -->
                                <span class="w12p">MultipleBuyer</span>
                                <!-- <span v-show="powerList.inquiry&&powerList.inquiry.inquiry_price.Isdisplay" :class="{ 'w6p': store.type != 4, 'w7p': store.type == 4 }">PRICE</span> -->
                                <span v-show="powerList.inquiry && powerList.inquiry.inquiry_price.Isdisplay"
                                    :class="powerList.inquiry && powerList.inquiry.inquiry_price.Isdisplay ? 'w6p' : 'w7p'">PRICE</span>
                                <span v-show="powerList.inquiry && powerList.inquiry.inquiry_profit.Isdisplay"
                                    style="width: 5.8%;">Profit</span>
                                <!-- <span v-show="powerList.inquiry&&powerList.inquiry.inquiry_cost.Isdisplay" :class="{ 'w6p': store.type != 3, 'w7p mr-5': store.type == 3 }">COST</span> -->
                                <span v-show="powerList.inquiry && powerList.inquiry.inquiry_cost.Isdisplay"
                                    :class="powerList.inquiry && powerList.inquiry.inquiry_cost.Isdisplay ? 'w6p' : 'w7p'">COST</span>
                                <!-- <span :class="{ 'w11p': store.type != 4, 'w15p': store.type == 4, 'w14p mr-5': store.type == 3 }">LEADING</span> -->
                                <span
                                    :class="powerList.inquiry && powerList.inquiry.inquiry_profit.Isdisplay ? 'w11p' : 'w15p'">LEADING</span>
                                <span
                                    :class="powerList.inquiry && powerList.inquiry.inquiry_profit.Isdisplay ? 'w11p' : 'w15p'">CONDITION</span>
                                <span style="width: 6.2%;">BUYER</span>
                                <span class="operation">OPERATION</span>
                            </p>
                            <el-checkbox-group v-model="checkedCities" @change="rightSelection">
                                <div v-for="table, index in production_item" :key="index" class="flex bbm jc-c pt-5 ml-10 ">
                                    <div class="flex w45p">
                                        <el-checkbox :label="table"><br></el-checkbox>
                                        <el-select class="w40p ml-5" v-model="table.product.model"
                                            :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_model.Isenable"
                                            :remote-method="getModel" @change="changeModel" @visible-change="visible"
                                            filterable remote placeholder="MODEL">
                                            <el-option v-for="item in newModel" :key="item.id" :label="item.label"
                                                :value="item.id" />
                                        </el-select>
                                        <el-select class="w40p " v-model="table.brand.brand_name"
                                            :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_brand.Isenable"
                                            :remote-method="getBrand" @visible-change="visible" filterable remote
                                            placeholder="BRAND">
                                            <el-option v-for="item in newBrand" :key="item.id" :label="item.label"
                                                :value="item.id" />
                                        </el-select>
                                        <div class=" w15p">
                                            <el-input v-model="table.Qty"
                                                :disabled="table.item.quotation_price != '' || !powerList.inquiry.inquiry_qty.Isenable"
                                                placeholder="QTY" />
                                        </div>
                                        <div class=" w40p">
                                            <el-select v-model="table.purchaser_id_list"
                                                :disabled="!powerList.inquiry.inquiry_multiplebuyer.Isenable"
                                                @remove-tag="delBuyer"
                                                @change="changeBuyer($event, table.purchaser_id_simple_list)" collapse-tags
                                                collapse-tags-tooltip placeholder="BUYER" multiple>
                                                <el-option v-for="item in newBuyer" :key="item.label" :label="item.label"
                                                    :value="item.id" />
                                            </el-select>
                                        </div>
                                    </div>
                                    <div class="flex fdc w55p">
                                        <div v-for="list in table.item_purchaser_array" class="flex  pb-5">
                                            <div v-show="powerList.inquiry.inquiry_price.Isdisplay" class=" w20p">
                                                <el-input v-model="list.quotation_price"
                                                    :disabled="!powerList.inquiry.inquiry_price.Isenable"
                                                    @input="inpPrice($event, list.purchase_price, list)" />
                                            </div>
                                            <div class="w20p">
                                                <div v-show="powerList.inquiry.inquiry_profit.Isdisplay" class="flex aic ">
                                                    <el-input v-model="list.profit_rate"
                                                        :disabled="!powerList.inquiry.inquiry_profit.Isenable"
                                                        @input="newSale($event, list.purchase_price, list)" />
                                                    <p class="f18">%</p>
                                                </div>
                                            </div>
                                            <div v-show="powerList.inquiry.inquiry_cost.Isdisplay" class="w20p ">
                                                <el-input v-model="list.purchase_price"
                                                    :disabled="!powerList.inquiry.inquiry_cost.Isenable"
                                                    @input="inpCost($event, list.profit_rate, list)" />
                                            </div>
                                            <el-select class="w40p " v-model="list.leadingtime"
                                                :disabled="!powerList.inquiry.inquiry_leading.Isenable" filterable
                                                placeholder="LEADING">
                                                <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                                    :value="item.case" />
                                            </el-select>
                                            <el-select class="w40p " v-model="list.product_condition"
                                                :disabled="!powerList.inquiry.inquiry_condition.Isenable" filterable
                                                placeholder="CONDITION">
                                                <el-option v-for="item in newCondition" :key="item.label"
                                                    :label="item.label" :value="item.case" />
                                            </el-select>
                                            <div class="buyer w20p ">
                                                <el-input v-model="list.name" disabled placeholder="BUYER" />
                                            </div>
                                            <!-- <div :class="{ 'w30p': store.type != 4, 'w25p': store.type == 4 }">
                                            </div> -->
                                            <div class="tabDel">
                                                <el-popconfirm title="Sure to delete?" @confirm="tabDel(list)">
                                                    <template #reference>
                                                        <el-button type="primary" size="small" plain
                                                            class="del">Delete</el-button>
                                                    </template>
                                                </el-popconfirm>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>

                <!-- 历史的供应商 -->
                <div class="brs bs mt-10 pt-10 pl-10 pr-10 ">
                    <p class="fwb fa5">Histroy RFQ</p>
                    <el-table :data="historyRfo" v-loading="historyLoading" height="26.5vh" style="width: 100%">
                        <el-table-column type="expand">
                            <template #default="props">
                                <div m="4">
                                    <el-table :data="props.row.inquiryItemInfo" border>
                                        <el-tbble-column align="center" prop="dco" label="DCO"></el-tbble-column>
                                        <el-table-column align="center" prop="Qty" label="Qty" />
                                        <el-table-column align="center" prop="item.quotation_price" label="PRICE" />
                                        <el-table-column align="center" prop="item.profit" label="Profit" />
                                        <el-table-column align="center" prop="item.purchase_price" label="COST" />
                                        <el-table-column align="center" prop="leading" label="LEADING">
                                            <template v-slot="leading">
                                                <el-select v-model="leading.row.item.leadingtime" filterable disabled
                                                    placeholder="Select">
                                                    <el-option v-for="item in newLeading" :key="item.label"
                                                        :label="item.label" :value="item.case" />
                                                </el-select>
                                            </template>
                                        </el-table-column>
                                        <!-- <el-table-column align="center" prop="sta" label="STA" /> -->
                                    </el-table>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="inquiry_id" align="center" label="RFQ ID" min-width="140" />
                        <el-table-column prop="country.name" align="center" label="CNTY" />
                        <el-table-column prop="items_count" align="center" label="ITEMS" />
                        <el-table-column prop="customer.Customer_type" align="center" label="SUPPLIER" min-width="90" />
                        <el-table-column prop="state" align="center" label="STA" />
                    </el-table>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import * as $axios from '../../../../api/index'
import useBrand from '../../../../hooks/useBrand'
import useModel from '../../../../hooks/useModel'
import * as echarts from "echarts";
import custom from '../../../../assets/custom.json'
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../../../pinia/index'
import usePower from "../../../../hooks/usePower";
const store = useDemoStore()
echarts.registerTheme('custom', custom)
const { powerList } = usePower()

// 接收父元素传过来的值
const props = defineProps({
    newLeading: Array,
    newCondition: Array
})

// 加载
const loading = ref(false)
const historyLoading = ref(false)
const historyQuotation = ref(false)

// 选择器打开关闭的时候触发
const visible = () => {
    OrderCapture()
    getModel()
    getBrand()
}

// 获取订单列表
const PI_name = ref('')
const orderList = ref([])
const OrderCapture = (text) => {
    const data = {
        token: store.token,
        keywords: text || ''
    }
    $axios.$orderOrder_list(data).then(res => {
        orderList.value = res.data.data
        getBuyer() //触发getBuyer事件把采购id变成采购名
        // console.log(res.data.data)
    })
}

// 选择器选项值方式改变时触发
const newOrder_id = ref('')
const quotationTable = ref([]) // 获取报价信息
const production_item = ref([])
const orderId = ref('')
const orderChange = (id) => {
    loading.value = true
    historyLoading.value = true
    historyQuotation.value = true
    orderId.value = id || orderId.value
    const data = {
        token: store.token,
        order_id: id || orderId.value
    }
    $axios.$orderOrder_info(data).then(res => {
        loading.value = false
        quotationTable.value = res.data.itemOrder
        production_item.value = res.data.inquiryItem
        newOrder_id.value = res.data.order_id
        // console.log(newOrder_id.value)
        profit.value = ''  //清空批量利润选择框
        leading.value = ''
        changeModel()
        product_id.value = quotationTable.value[0] && quotationTable.value[0].product_id //拿数组的第一个product_id
        model.value = quotationTable.value[0] && quotationTable.value[0].product_name_pi
        getHistory_quotation() //调用折线图
        getHistoryRfo()  // 调用右边历史询盘表格
    })
}

// 图表
const price = ref()

// 弹窗
const quotation = ref(false)
const poseQuotation = () => {
    quotation.value = true
    // production_item.value = [] //清空数组
    nextTick(() => {
        quote()
    })
}


// 左边多选框
const inquiry = ref([])
const order_id = ref('')
const handleSelectionChange = (data) => {
    inquiry.value = data.map(item => {
        return item.order_info_id
    })
    console.log(data)
    data.forEach(item => {
        order_id.value = item.order_id
    })
}

// 点击左边table
const product_id = ref('')
const model = ref('') //图表标题
const graph = (data) => {
    // console.log(data.product_id)
    product_id.value = data.product_id
    model.value = data.product_name_pi
    getHistory_quotation()
    getHistoryRfo()
}

// 折线图数据
const history_quotation = ref([])
const getHistory_quotation = () => {
    historyQuotation.value = true
    const data = {
        token: store.token,
        product_id: product_id.value || ''
    }
    $axios.$history_quotation(data).then(res => {
        historyQuotation.value = false
        history_quotation.value = res.data
        quote()
    })
}

// 右边历史询盘表格
const historyRfo = ref([])
const getHistoryRfo = () => {
    historyLoading.value = true
    const data = {
        token: store.token,
        product_id: product_id.value || ''
    }
    $axios.$pollingInquiry_history(data).then(res => {
        historyLoading.value = false
        console.log(res)
        historyRfo.value = res.data.data
    })
}

// 添加到右边
const add = () => {
    const data = {
        token: store.token,
        order_id: order_id.value,
        order_info_id: inquiry.value
    }
    $axios.$orderOrder_product(data).then(res => {
        if (production_item.value.some(item => item.msg == '1')) { //添加到新建的
            console.log(res.data)
            production_item.value = []
            production_item.value = [
                ...production_item.value,
                ...res.data
            ]
            production_item.value.push({
                "msg": 1,
                "Qty": '',
                "msg": 1,
                "index": Math.round(Math.random() * (9000 - 100) + 100),
                "product": {
                    "model": ''
                },
                "purchaser_array": [],
                "purchaser_id_list": [],
                "item_purchaser_array": [
                    {
                        "purchaser_id": '',
                        "quotation_price": "",
                        "profit_rate": '',
                        "purchase_price": '',
                        "leadingtime": "",
                        "product_condition": ""
                    },
                ],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "quotation_price": ''
                }
            })
        } else {
            production_item.value.pop()
            production_item.value = [
                ...production_item.value,
                ...res.data,
            ]
            production_item.value.push({
                "Qty": '',
                "msg": 1,
                "index": Math.round(Math.random() * (9000 - 100) + 100),
                "product": {
                    "model": ''
                },
                "purchaser_array": [],
                "purchaser_id_list": [],
                "item_purchaser_array": [
                    {
                        "purchaser_id": '',
                        "quotation_price": "",
                        "profit_rate": '',
                        "purchase_price": '',
                        "leadingtime": "",
                        "product_condition": ""
                    },
                ],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "quotation_price": ''
                }
            })
        }
        // console.log(res.data)
    })
}


// 采购多选框取消选择的时候
const changeBuyer = (val, arr) => {
    const list = val.concat(arr).filter((v, i, arrList) => {  //找出被取消的采购
        return arrList.indexOf(v) === arrList.lastIndexOf(v)
    })
    production_item.value.forEach(item => {
        list.forEach(arr2 => {
            const index = item.item_purchaser_array.findIndex(i => i.id == arr2)   //找出被取消的采购所在的位置
            if (index == -1) return
            item.item_purchaser_array.splice(index, 1) //删除数组
            if (item.item_purchaser_array.length == 0) { //如果数组长度为0时，添加一个空数组
                item.item_purchaser_array.push({
                    "purchaser_id": '',
                    "quotation_price": "",
                    "profit_rate": '',
                    "purchase_price": '',
                    "leadingtime": "",
                    "product_condition": ""
                })
            }
        })
    })
}

// model
var newModel = ref([])
const getModel = (text) => {
    newModel.value = { newModel } = useModel(text)
}

// brand
var newBrand = ref([])
const getBrand = (text) => {
    newBrand.value = { newBrand } = useBrand(text)
}

//Buyer(获取销售与采购人员列表)
const newBuyer = ref([])
const getBuyer = () => {
    const data = {
        token: store.token,
        keywords: '采购'
    }
    $axios.$userUser_list(data).then(res => {
        newBuyer.value = res.data.map(item => {
            return {
                'label': item.name,
                'id': item.id
            }
        })
        // console.log(res.data)
    })
}


// 利润数据
const profit = ref('')
const profitArr = ref([
    {
        label: '10%',
        value: 10
    },
    {
        label: '15%',
        value: 15
    },
    {
        label: '20%',
        value: 20
    },
    {
        label: '25%',
        value: 25
    },
    {
        label: '30%',
        value: 30
    },
    {
        label: '35%',
        value: 35
    },
    {
        label: '40%',
        value: 40
    },
    {
        label: '45%',
        value: 45
    },
    {
        label: '50%',
        value: 50
    },
])

// 批量更改利润
const unifiedProfit = (data) => {
    production_item.value.forEach(item => {
        item.item_purchaser_array.forEach(arr => {
            if (arr.quotation_price && arr.purchase_price) {
                arr.profit_rate = data
                arr.quotation_price = ((data / 100) * (arr.purchase_price || 0 * 1) + (arr.purchase_price || 0) * 1).toFixed(2)
            }
        })
        // console.log(item)
    })
}


// 批量更改指标
const leading = ref('')
const unifiedLeading = (data) => {
    production_item.value.forEach(item => {
        if (item.product.model) {
            item.item_purchaser_array.forEach(arr => {
                arr.leadingtime = data
            })
        }
        // console.log(item)
    })
}

// 获取利润，计算售出价
const getprofit = ref(0)
const newSale = (e, value, data) => {  //获取利润
    getprofit.value = ((e / 100) * (value || 0 * 1) + (value || 0) * 1).toFixed(2)   //计算售出价
    data.quotation_price = getprofit.value
}

// 获取售出价,计算利润
const newProfit = ref()  //利润
const inpPrice = (e, value, data) => {
    newProfit.value = ((e - value * 1) / value * 100).toFixed(2)  //计算利润比
    data.profit_rate = value * 1 ? newProfit.value : 0
}


// 获取成本价,计算售出价
const tmoney = ref(0)  //售出价
const inpCost = (e, value, data) => {
    tmoney.value = (e * ((value || 0) / 100) + e * 1).toFixed(2)  //计算售出价
    data.quotation_price = tmoney.value
}


// 新增
const Added = () => {
    if (!!newOrder_id.value) {
        production_item.value = []
        for (let i = 0; i <= 5; i++) {
            production_item.value.push({
                "Qty": '',
                "msg": 1,
                "index": Math.round(Math.random() * (9000 - 100) + 100),
                "product": {
                },
                "purchaser_array": {

                },
                "item_purchaser_array": [
                    {
                        "purchaser_id": '',
                        "quotation_price": "",
                        "profit_rate": '',
                        "purchase_price": '',
                        "leadingtime": "",
                        "product_condition": ""
                    },
                ],
                "purchaser_id_list": [],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "quotation_price": ''
                }
            })
        }
    } else {
        ElMessage({
            duration: 2000,
            message: 'Please select the order',
            type: 'warning',
        })
    }
}

// 判断输入框是否为空，不为空就添加一个空的输入框
const changeModel = () => {
    // console.log(production_item.value[production_item.value.length-1])
    const model = production_item.value[production_item.value.length - 1] && production_item.value[production_item.value.length - 1].product.model
    const addModel = production_item.value[production_item.value.length - 1]
    if (model || addModel == undefined) {
        production_item.value.push({
            "Qty": '',
            "product": {
            },
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "purchaser_array": {

            },
            "purchaser_id_list": [],
            "item_purchaser_array": [
                {
                    "purchaser_id": '',
                    "quotation_price": "",
                    "profit_rate": '',
                    "purchase_price": '',
                    "leadingtime": "",
                    "product_condition": ""
                },
            ],
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
                "quotation_price": ''
            }
        })
    }
    // console.log(model)
}

// 右边全选
const checkAll = ref(false)
const isIndeterminate = ref(false)
const handleCheckAllChange = (val) => {
    checkedCities.value = val ? production_item.value : []
    isIndeterminate.value = false
    rightSelection(checkedCities.value)
}

// 右边多选框
const checkedCities = ref([])
const inquiryId = ref([])
const random = ref([])
const rightSelection = (value) => {
    console.log(value)
    inquiryId.value = []
    random.value = []
    checkAll.value = value.length === production_item.value.length
    isIndeterminate.value = value.length > 0 && value.length < production_item.value.length

    value.forEach(item => {
        if (item.index) {
            random.value.push(item.index)
        } else {
            item.item_purchaser_array.forEach(arr => {
                inquiryId.value.push(arr.inquiry_item_info_id)
            })
        }
    })
    // console.log(random.value)
}

// 删除
const delGoods = () => {
    if (inquiryId.value.length > 0 || random.value.length > 0) {
        if (inquiryId.value.length > 0) {
            const data = {
                token: store.token,
                inquiry_item_info_id: inquiryId.value
            }
            $axios.$pollingDel(data).then(res => {
                // orderChange()
                inquiryId.value.forEach(item => {
                    const index = production_item.value.findIndex(arr => arr.inquiry_item_info_id == item)
                    index != -1 && production_item.value.splice(index, 1)  //删除数组里面的成员
                })
                ElMessage({
                    message: 'successfully delete',
                    type: 'success',
                })
                console.log(res)
            })
        }
        if (random.value.length > 0) {
            random.value.forEach(item => {
                const index = production_item.value.findIndex(arr => arr.index == item)
                index != -1 && production_item.value.splice(index, 1)  //删除数组里面的成员
            })
        }
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }
}

// 删除单个采购
const tabDel = (val) => {
    console.log(val)
    const data = {
        token: store.token,
        inquiry_item_info_id: val.inquiry_item_info_id
    }
    $axios.$pollingDel(data).then(res => {
        if (res.Status === 0) {
            production_item.value.forEach(item => {
                const index = item.item_purchaser_array.findIndex(arr => arr.inquiry_item_info_id == val.inquiry_item_info_id)
                index != -1 && item.item_purchaser_array.splice(index, 1)
                index != -1 && item.purchaser_id_list.splice(index, 1)
                if (item.item_purchaser_array.length == 0) {
                    const index = production_item.value.findIndex(arr => arr.inquiry_item_info_id == val.inquiry_item_info_id)
                    index != -1 && production_item.value.splice(index, 1)
                }
            })

            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        }
    })
}

// 需要保存的数据
const dataArr = (arr) => {
    // console.log(arr)
    newArr.value = arr.map(item => {
        return {
            "order_id": newOrder_id.value,
            "product_id": typeof item.product.model == 'string' ? item.product.product_id : item.product.model,
            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
            "inquiry_id": item.inquiry_id || '',
            "purchaser_id": item.id || '',
            "inquiry_item_info_id": item.inquiry_item_info_id || '',
            'model': item.product.model,
            'qty': item.Qty || 0,
            'quotation_price': item.quotation_price || '',
            'profit_rate': item.profit_rate || '',
            'price': item.purchase_price || '',
            // 'purchase_price': item.purchase_price,
            'leadingtime': item.leadingtime || '',
            'product_condition': item.product_condition || '',
        }
    })
}

// 保存
const newArr = ref([])
const save = () => {
    const arr = ref([])
    production_item.value.forEach((items) => {
        // 判断是否有model有就是要进行提交的
        if (items.product.model) {
            if (items.purchaser_id_list && items.purchaser_id_list.length != 0) {  //选择采购
                items.purchaser_id_list && items.purchaser_id_list.forEach((name, index) => {
                    arr.value.push({
                        ...items,
                        ...items.item_purchaser_array[index],
                        id: name,
                        inquiry_item_info_id: items.purchaser_array[index] && items.purchaser_array[index].inquiry_item_info_id
                    })
                    dataArr(arr.value)
                })
            } else { //不选择采购
                arr.value.push({
                    ...items,
                })
                dataArr(arr.value)
            }
        }
    });

    console.log(newArr.value)
    if (newArr.value.length != 0) {
        const data = {
            token: store.token,
            product: newArr.value,
            inquiry_id: arr.value[0].inquiry_id
        }
        if (production_item.value[0].msg === 1) {    //判断是不是新增的
            // console.log('新增订单转询盘')
            $axios.$quotationNew_quotation(data).then(res => {
                // console.log(res)
                if (res.Status == 0) {
                    quotation.value = false
                    emits('quote') //触发事件，更新页面
                    orderChange()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save failed',
                        type: 'warning',
                    })
                }
            })
        } else {
            $axios.$quotationSave_quotation(data).then(res => {
                // console.log(res)
                if (res.Status == 0) {
                    orderChange()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save failed',
                        type: 'warning',
                    })
                }
            })
        }
    } else {
        ElMessage({
            message: 'Please choose model brand',
            type: 'warning',
        })
    }
}
const emits = defineEmits(['quote'])

// 暴露方法
defineExpose({
    poseQuotation
})

// 添加到报价的图表
var myChart
const quote = () => {
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(price.value, 'custom');
    var option = {
        title: {
            text: model.value
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#fff'
                }
            }
        },
        legend: {
            data: ['Histroy quotation']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Histroy quotation',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: history_quotation.value
            }
        ]
    };
    option && myChart.setOption(option);
    window.addEventListener("resize", myChart.resize) //自动缩放
}
</script>

<style lang="less" scoped>
.addQuotation {
    .brs {
        border-radius: 10px;
    }

    .addLeft {
        width: 50%;
        padding-right: 10px;
    }

    .rightPrice {
        // border: 1px solid red;
        width: 50%;

        .boxTable {
            height: 39vh;
            overflow: hidden;

            .table {
                width: 65vw;
                // border: 1px solid red;
            }

            .bbm {
                border-bottom: 1px solid #EBEEF5;
            }

            .tabTitle {
                position: sticky;
                top: 0;
                background-color: #fff;
                z-index: 9;
            }
        }

        .boxTable:hover {
            overflow: overlay;
        }

        ::-webkit-scrollbar {
            height: 5px;
            width: 5px;
        }

        ::-webkit-scrollbar-track {
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            border-radius: 10px;
            background-color: #C8C9CC;
        }
    }

    .add.el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: #ecf5ff;
    }


    .el-button.is-plain {
        border: 1px solid #6193D2;
        color: #6193D2;
        background-color: #fff;
    }

    .del.el-button.is-plain {
        border: 1px solid #6193D2;
        color: #fff;
        background-color: #6393D4;
    }

    .operation {
        // border: 1px solid red;
        text-align: center;
        width: 90px;
        right: 0%;
        position: sticky;
        background-color: #fff;
    }

    .tabDel {
        // border: 1px solid red;
        height: 38px;
        padding-top: 3px;
        width: 102px;
        padding-left: 15px;
        padding-right: 15px;
        display: flex;
        justify-content: center;
        position: sticky;
        right: 0%;
        background-color: #fff;
        z-index: 5;
    }

    .w6p {
        width: 6%;
    }



    .w7p {
        width: 7.6%;
    }

    .w6-5 {
        width: 6.5%;
    }

    .w11p {
        width: 12%;
        // border: 1px solid red;
    }

    .w12p {
        width: 12.3%;
    }

    .w13p {
        width: 13%;
    }

    .w13-6p {
        width: 13.6%;
    }

    .w14p {
        width: 14%;
    }

    .w15p {
        width: 15.2%;
    }
}</style>